package com.gitee.feizns.quickstart.mybatis.flex.jpa;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gitee.feizns.quickstart.domain.tree.TreeNode;
import com.mybatisflex.core.query.QueryChain;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author feizns
 * @since 2025/9/21
 */
public interface TreePojo<T extends TreePojo<T, ID>, ID> extends TreeNode<T, ID> {

    /**
     * 是否是根
     * @return boolean
     */
    @JsonIgnore
    default boolean isRoot() {
        return TreeNode.super.isRoot();
    }

    /**
     * 父节点
     * @return {@link T }
     */
    @SuppressWarnings("unchecked")
    default T parent() {
        return isRoot() ? null : (T) QueryChain.of(this.getClass()).eq(T::getId, getParentId()).one();
    }

    /**
     * 子项列表
     * @return {@link List }<{@link T }>
     */
    @SuppressWarnings("unchecked")
    default List<T> children() {
        return (List<T>) QueryChain.of(this.getClass()).eq(T::getParentId, this.getId()).list();
    }

    /**
     * 子编号列表
     * @return {@link List }<{@link Long }>
     */
    default List<ID> subIdList() {
        //noinspection unchecked
        List<T> list = (List<T>) QueryChain.of(this.getClass()).eq(T::getParentId, this.getId()).select(T::getId).list();
        return list.stream().map(T::getId).collect(Collectors.toList());
    }

    /**
     * 是否有子项
     * @return boolean
     */
    default boolean hasChildren() {
        return QueryChain.of(this.getClass()).eq(T::getParentId, this.getId()).exists();
    }

}
